package cn.gs.serializable.entity;

// @author gs
import cn.gs.serializable.old.SerialTransport;
import cn.gs.util.stream.TokenReader;
import java.io.IOException;
import java.io.Writer;

public class OneEntity implements IEntity {

    private String value;
    private boolean quote;

    public OneEntity() {
        this(null, false);
    }

    public OneEntity(String value) {
        this(value, false);
    }

    public OneEntity(String value, boolean quote) {
        this.value = value;
        this.quote = quote;
    }

    @Override
    public boolean read(EntityController ctrl, TokenReader reader) throws IOException {
        this.value = reader.get();
        if (reader.isEndChar(value)) {
            if ("\"".equals(value)) {
                //String
                quote = true;
                StringBuilder sb = new StringBuilder();
                do {
                    String t = reader.get();
                    if ("\"".equals(t)) {
                        this.value = sb.toString();
                        break;
                    }
                    sb.append(t);
                    while (t.length() > 0 && '\\' == t.charAt(t.length() - 1)) {
                        t = reader.get();
                        sb.append(t);
                    }
                } while (true);
            } else {
                reader.back();
                return false;
            }
        }
        this.value = decode(value);
        return true;
    }

    @Override
    public void write(EntityController ctrl, Writer writer) throws IOException {
        String s = toString();
        writer.write(s);
    }

    @Override
    public String toString(String prefix) {
        return prefix + toString();
    }

    @Override
    public String toString() {
        if (isQuote()) {
            return "\"" + (null == value ? "NULL" : encode(value)) + "\"";
        } else {
            return null == value ? "NULL" : encode(value);
        }
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public static String encode(String str) {
        String s = str.replace("\\", "\\\\").replace("\"", "\\\"").replace("/", "\\/").replace("\b", "\\b").replace("\f", "\\f").replace("\n", "\\n").replace("\r", "\\r").replace("\t", "\\t");
        return s;
    }

    public static String decode(String str) {
        String s = str.replace("\\\\", "\\m").replace("\\t", "\t").replace("\\r", "\r").replace("\\n", "\n").replace("\\f", "\f").replace("\\b", "\b").replace("\\/", "/").replace("\\\"", "\"").replace("\\m", "\\");
        return s;
    }

    public boolean isQuote() {
        return quote;
    }
}
